package com.rasou.jms;

import com.rasou.AbstractListener;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.EventObject;

public class JmsListener extends AbstractListener {

    private final ActiveMQConnectionFactory activeMQConnectionFactory;

    public JmsListener(String url) {
        this.activeMQConnectionFactory = new ActiveMQConnectionFactory(url);
    }

    @Override
    protected void sendToRemote(EventObject event) {
        MessageProducer producer = null;
        Session session = null;
        Connection connection = null;

        try {
            connection = activeMQConnectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(Constant.TOPIC_NAME);

            producer = session.createProducer(topic);
            TextMessage message = session.createTextMessage(event.getSource().toString());
            producer.send(message);
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if (producer != null) {
                try {
                    producer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
